package com.xymtop.api.config;

/**
 * @ClassName : WebSocketController
 * @Description :
 * @Author : 肖叶茂
 * @Date: 2022/12/9  12:20
 */
import com.xymtop.api.entity.LiveMsg;
import com.xymtop.api.service.UserService;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/live")
@Component
public class MyWebSocket {

    @Autowired
    private UserService userService;

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

//    设置直播id
    private  static CopyOnWriteArraySet<String> LiveRooms  = new CopyOnWriteArraySet<String>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private  String liveId;
    private  String username;



    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        Map<String, List<String>> listMap = session.getRequestParameterMap();
        this.liveId = String.valueOf(listMap.get("liveid"));
        this.username = String.valueOf(listMap.get("name"));
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("have new conn " + getOnlineCount() + this.liveId + "  "+this.username);

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        LiveRooms.remove(this);
        subOnlineCount();           //在线数减1
        System.out.println("the conn is" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("have msg :" + message);


//        下面处理消息
        JSONObject object =JSONObject.fromObject(message);
        LiveMsg msg = (LiveMsg) (JSONObject.toBean(object,LiveMsg.class));

            // 执行信令
        ExecCmd(msg);
    }


    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        System.out.println("send"+ message);
        //this.session.getAsyncRemote().sendText(message);
    }

//    处理信令
    public void ExecCmd(LiveMsg msg) throws IOException {
//        System.out.println(msg);
        if(msg.getLiveid()!=null){
            LiveMsg rmsg = new LiveMsg();
            rmsg.setUserid(msg.getUserid());
            rmsg.setMsg(msg.getMsg());
            JSONObject object =JSONObject.fromObject(rmsg);
            sendLiveMsg(msg.getLiveid(), object.toString());
        }
    }





//    发送直播间的消息
    private  void sendLiveMsg(String liveId,String str) throws IOException {


        for(MyWebSocket socket:webSocketSet){

            if(socket.liveId!=null&&socket.liveId.equals("["+liveId+"]")){
                socket.sendMessage(str);
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }



}